﻿using System;
using System.IO;
using csvm.contracts.components.Metadaten;
using csvm.contracts.datamodel;

//FIXME Traceinformation
namespace csvm.metadatenrepo
{
    public class MetadatenkopfSchreiben : IMetadatenkopfSchreiben
    {
        private const byte VersionByte = 1;

        public void In_Schreiben(AnalyseParameter parameter)
        {
            var eightBytesdatensatzAnzahl = BitConverter.GetBytes(0L);
            var lastModificationCsvFile = File.GetLastWriteTime(parameter.CSVDateiname);
            var csvFileIdByteArray = GetDateTimeAsByteArray(lastModificationCsvFile);
            var csvFilenameByteArray = GetStringAsByteArray(parameter.CSVDateiname);
            var twoBytesNewLine = GetStringAsByteArray(Environment.NewLine);
            
            WriteByteArraysToFile(parameter.MetadatenDateiname, eightBytesdatensatzAnzahl, csvFileIdByteArray, csvFilenameByteArray, twoBytesNewLine);
            Out_Geschrieben();
        }

        public event Action Out_Geschrieben;

        internal void WriteByteArraysToFile(String metadatenDateiname, byte[] datensatzAnzahl, byte[] csvFileId, byte[] csvFilename, byte[] newLine)
        {
            using (var metadatenStream = File.Create(metadatenDateiname))
            {
                metadatenStream.WriteByte(VersionByte);
                WriteByteArrayToFileStream(datensatzAnzahl, metadatenStream);
                WriteByteArrayToFileStream(csvFileId, metadatenStream);
                WriteByteArrayToFileStream(csvFilename, metadatenStream);
                WriteByteArrayToFileStream(newLine, metadatenStream);
            }
        }


        private void WriteByteArrayToFileStream(byte[] byteArray, FileStream metadatenStream)
        {
            metadatenStream.Write(byteArray, 0, byteArray.Length);
        }

        internal byte[] GetDateTimeAsByteArray(DateTime lastModificationCsvFile)
        {
            var lastModifiacationCsvFileBytes = BitConverter.GetBytes(lastModificationCsvFile.ToBinary());
            return lastModifiacationCsvFileBytes;
        }

        internal byte[] GetStringAsByteArray(string stringToConvert)
        {
            var enc = new System.Text.UTF8Encoding();
            return enc.GetBytes(stringToConvert);
        }
    }
}